# -*- coding: utf-8 -*-

###########################################################################
#
#   Copyright (c) 2020  Bresee, Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###########################################################################

# annual fee management 年费管理

from builtins import print
from calendar import c
from flask import Blueprint
from flask import request
import utils.pgsql.pgannualfee
from utils.wraps import token, urlcost
import utils.message.response as response
import json
import utils.pgsql.pgcase
import datetime

annualfee_module = Blueprint(
    "annualfee_annualfeement", __name__, url_prefix="/api/v1/annualfee/annualfeement"
)

@annualfee_module.route("/case/edit/<int:caseId>", methods=["POST"])
@token.login_required
@urlcost.cost_count_wraps
def case_edit(caseId):
    
    userInfo = token.getUserInfoFromAuth(request.headers["Authorization"])
    if userInfo["role"] in [1, 2, 3]:
        obj = utils.pgsql.pgcase.PgCase()
        dic = json.loads(request.data)
        print(dic)
        now = datetime.datetime.now()
        old = now + datetime.timedelta(int(dic["equipmentFor"]["duration"]))
        if obj.modify(dic, "caseId", caseId):
            if dic["auditatatus"] == "审核成功":
                annualobj = utils.pgsql.pgannualfee.PgAnnualfee()
                deviceNum = len(annualobj.get_deviceNum(caseId)) + 1
                for i in range(int(json.loads(dic["equipmentFor"])["equipmentNum"])):
                    annualobj.add(
                        {
                            "caseId": caseId,
                            "uniqueCode": str(caseId).zfill(4)
                            + "-"
                            + now.strftime("%Y%m%d")
                            + "-"
                            + str(deviceNum + i).zfill(4),
                            "expirationDate": old.strftime("%Y%m%d"),
                        }
                    )
                obj.modify(   
                    {
                        "equipmentFor": {
                            "equipmentNum": 0,
                            "duration": 30,
                        }
                    },
                    "caseId",
                    caseId,
                )
            return response.make_response_success_no_data()
        else:
            return response.make_response_1000()
    else:
        return response.make_response_401()


@annualfee_module.route("/<int:caseId>", methods=["GET"])
@token.login_required
@urlcost.cost_count_wraps
def annual_case(caseId):
    annualobj = utils.pgsql.pgannualfee.PgAnnualfee()
    return response.make_response_success(annualobj.get_deviceNum(caseId))


@annualfee_module.route("/unuse/<int:caseId>", methods=["GET"])
@token.login_required
@urlcost.cost_count_wraps
def annual_unuse(caseId):
    annualobj = utils.pgsql.pgannualfee.PgAnnualfee()
    return response.make_response_success(annualobj.get_unusedevice(caseId))


@annualfee_module.route("/annual/auditatatus", methods=["GET"])
@token.login_required
@urlcost.cost_count_wraps
def annual_auditatatus():
    annualobj = utils.pgsql.pgannualfee.PgAnnualfee()
    return response.make_response_success(annualobj.get_auditatatus())


@annualfee_module.route("/annual/data", methods=["GET"])
@token.login_required
@urlcost.cost_count_wraps
def annual_data():
    annualobj = utils.pgsql.pgannualfee.PgAnnualfee()
    return response.make_response_success(annualobj.get_data())


@annualfee_module.route("/case/auditatatus", methods=["GET"])
@token.login_required
@urlcost.cost_count_wraps
def case_auditatatus():
    obj = utils.pgsql.pgcase.PgCase()
    return response.make_response_success(obj.get_auditatatus())


@annualfee_module.route("/data", methods=["GET"])
def case_data():
    annualobj = utils.pgsql.pgannualfee.PgAnnualfee()
    annual = annualobj.get_all()
    now = datetime.datetime.now()
    for i in annual:
        expirationDate = datetime.datetime.strptime(i["expirationDate"], "%Y%m%d")
        expirationDate = datetime.date(
            expirationDate.year, expirationDate.month, expirationDate.day
        )
        now = datetime.date(now.year, now.month, now.day)
        data = (expirationDate - now).days
        dic = {}
        dic["data"] = data
        if data < 0:
            dic["activation"] = 0
        annualobj.modify(i["annualfeeId"], dic, "annualfeeId")
    return response.make_response_success([])


@annualfee_module.route("/annualfee/<int:annualfeeId>", methods=["PUT"])
@token.login_required
@urlcost.cost_count_wraps
def annual_device(annualfeeId):
    dic = json.loads(request.data)
    annualobj = utils.pgsql.pgannualfee.PgAnnualfee()
    if annualobj.modify(annualfeeId, dic, "annualfeeId"):
        if dic["auditatatus"] == "审核成功":
            duration = 0
            if dic["equipmentFor"] == "临时设备":
                duration = 30
            else:
                duration = 365
            print(dic["equipmentFor"])
            expirationDate = annualobj.get_annualfeeId(annualfeeId)["expirationDate"]
            expirationDate = (
                datetime.datetime.strptime(expirationDate, "%Y%m%d")
                + datetime.timedelta(duration)
            ).strftime("%Y%m%d")
            annualobj.modify(
                annualfeeId,
                {"equipmentFor": "", "expirationDate": expirationDate},
                "annualfeeId",
            )
            return response.make_response_success({"expirationDate": expirationDate})
        return response.make_response_success_no_data()
    else:
        return response.make_response_401()


#    
#      
#   
#      
#     userInfo = token.getUserInfoFromAuth(request.headers["Authorization"])

#     obj = channel.PgChannel()

#     if userInfo['role'] == 2:
#         operatorId = userInfo['operatorId']
#         return response.make_response_success(obj.allunchanneloperator(operatorId))
#     elif userInfo['role'] == 3:
#         operatorId = userInfo['operatorId']
#         caseId = userInfo['caseId']
#         return response.make_response_success(obj.allunchannelcase(operatorId, caseId))
#     else:
#         return response.make_response_401()

# @channel_module.route('/', methods=['POST'])
# @token.login_required
# @urlcost.cost_count_wraps
# def point_add():
#      
#      
#      
#     
#     userInfo = token.getUserInfoFromAuth(request.headers["Authorization"])
#     if userInfo['role'] in [2, 3]:
#         obj = channel.PgChannel()
#         dic = json.loads(request.data)
#         channelappinfor = ""
#         data = {}
#         data['check_path'] = True
#         data['env_version'] = "release"

#         if 'pagePath' in dic:
#             #print(obj.channelname(dic['channelName'], dic['caseId']))
#             #print(obj.caseorcode(dic['pagePath'], dic['caseId']))
#             if obj.channelname(dic['channelName'], dic['caseId']) != []:
#                 # obj.delete(res["channelId"])
#                 return response.make_response_1505()
#             if obj.caseorcode(dic['pagePath'], dic['caseId']) != []:
#                 # obj.delete(res["channelId"])
#                 return response.make_response_1530()
#             res = obj.addChannel(dic)
#             data['scene'] = "caseId="+str(dic['caseId']) + ",channelId=-1"
#         else:
#             if obj.sellerId(dic['sellerId']) != []:
#                 return response.make_response_1530()
#             res = obj.addChannel(dic)
#             data['scene'] = "caseId=" + \
#                 str(dic['caseId']) + ",channel" + str(res['channelId'])
#         if userInfo['operatorId'] == 1:
#             data['page'] = 'pages/customCamera/cameras'
#             channelappinfor = " "
#         else:
#             channelappinfor = " "
#             data['page'] = 'pages/index/index'

#         url = 'http://127.0.0.1:33033/api/v1/channel/channelment/weixin'
#         infor = {
#             "channelappinfor": channelappinfor,
#             "data": json.dumps(data),
#             "channelId": res['channelId']
#         }
#         body = json.dumps(infor)
#         res = requests.post(url, body, headers={
#                             "content-type": "application/json"})
#         return json.loads(res.text)


# @channel_module.route('/unchannel', methods=['GET'])
# @token.login_required
# @urlcost.cost_count_wraps
# def unchannel():
#     
#      
#      
#      
#     userInfo = token.getUserInfoFromAuth(request.headers["Authorization"])

#     obj = channel.PgChannel()

#     if userInfo['role'] == 2:
#         operatorId = userInfo['operatorId']
#         return response.make_response_success(obj.allunchanneloperator(operatorId))
#     elif userInfo['role'] == 3:
#         operatorId = userInfo['operatorId']
#         caseId = userInfo['caseId']
#         return response.make_response_success(obj.allunchannelcase(operatorId, caseId))
#     else:
#         return response.make_response_401()


# @channel_module.route('/weixin', methods=['POST'])
# @urlcost.cost_count_wraps
# def weixin():
#     obj = channel.PgChannel()
#     data = request.get_data()
#     dic = json.loads(data)
#     try:
#         response3 = requests.get(dic["channelappinfor"],
#                                  headers={"content-type": "application/xml"})
#         access_token = json.loads(response3.text)['access_token']
#         response2 = requests.post("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + access_token,
#                                   dic["data"], headers={"content-type": "application/json"})
#         if("errcode" in str(response2.content)):
#             obj.delete(dic["channelId"])
#             return response.make_response_1000()
#         else:
#             filename = initres.UPLOADPATH + str(uuid.uuid1()) + ".png"
#             with open(filename, 'wb') as f:
#                 f.write(response2.content)

#             filename = oss.upload_webRes(filename)
#             log.logging.info(filename)
#             obj.modify(dic['channelId'], {'orCode': filename})
#             return response.make_response_success({"channelId": dic['channelId']})
#     except:
#         obj.delete(dic["channelId"])
#         return response.make_response_1004()


# @channel_module.route('/<int:channelId>', methods=['PUT'])
# @token.login_required
# @urlcost.cost_count_wraps
# def point_put(channelId):
#    
#    
#    
#     
#     # tokenInfo = request.headers["Authorization"]
#     userInfo = token.getUserInfoFromAuth(request.headers["Authorization"])
#     if userInfo['role'] in [2, 3]:
#         obj = channel.PgChannel()
#         dic = json.loads(request.data)
#         if "channelName" in dic:
#             if obj.channeleditname(dic['channelName'], dic['caseId'], channelId) != []:
#                 return response.make_response_1505()
#         if obj.modify(channelId, dic):
#             return response.make_response_success_no_data()
#         else:
#             return response.make_response_1000()
#     else:
#         return response.make_response_401()


# @channel_module.route('/<int:channelId>', methods=['DELETE'])
# @token.login_required
# @urlcost.cost_count_wraps
# def point_delete(channelId):
#      
#      
#  
#      
#     userInfo = token.getUserInfoFromAuth(request.headers["Authorization"])

#     if userInfo['role'] in [2, 3]:
#         obj = channel.PgChannel()

#         if obj.delete(channelId):
#             return response.make_response_success_no_data()
#         else:
#             return response.make_response_1000()
#     else:
#         return response.make_response_401()


# @channel_module.route('/admin/<int:adminId>', methods=['GET'])
# @token.login_required
# @urlcost.cost_count_wraps
# def seller_all_admin(adminId):
#      
#      
#      
#    
#     userInfo = token.getUserInfoFromAuth(request.headers["Authorization"])

#     obj = channel.PgChannel()
#     if userInfo['role'] == 1:
#         return response.make_response_success(obj.all())
#     elif userInfo['role'] == 2:
#         operatorId = userInfo['operatorId']
#         return response.make_response_success(obj.allByoperator(operatorId))
#     elif userInfo['role'] == 3:
#         caseId = userInfo['caseId']
#         return response.make_response_success(obj.allBycaseId(caseId))
#     else:
#         return response.make_response_401()
